import SwiftUI
import SwiftData

struct ContentView: View {
    // To manage instances of your model classes at runtime, use a model context — the object responsible for the in-memory model data and coordination with the model container to successfully persist that data.
    // To get a context for your model container that’s bound to the main actor, use the modelContext environment variable:
    // the returned context periodically checks whether it contains unsaved changes, and if so, implicitly saves those changes on your behalf.
    @Environment(\.modelContext) private var modelContext
    // To fetch model instances, and optionally apply search criteria and a preferred sort order, use @Query in your SwiftUI view.
    // The @Model macro adds **Observable conformance** to your model classes, enabling SwiftUI to refresh the containing view whenever changes occur to any of the fetched instances.
    // @Query(sort: \.startDate, order: .reverse) var allTrips: [Trip]
    @Query(sort: \Item.timestamp, order: .reverse) private var items: [Item]

    var body: some View {
        NavigationSplitView {
            List {
                ForEach(items) { item in
                    NavigationLink {
                        Text("Item at \(item.timestamp, format: Date.FormatStyle(date: .numeric, time: .standard))")
                    } label: {
                        Text(item.timestamp, format: Date.FormatStyle(date: .numeric, time: .standard))
                    }
                }
                // 使用onDelete响应删除
                .onDelete(perform: deleteItems)
            }
            .toolbar {
                ToolbarItem {
                    // 使用action响应添加
                    Button(action: addItem) {
                        Label("Add Item", systemImage: "plus")
                    }
                }
                ToolbarItem {
                    EditButton()
                }
            }
        } detail: {
            Text("Select an item")
        }
    }

    private func addItem() {
        withAnimation {
            let newItem = Item(timestamp: Date())
            // Following the insert, you can save immediately by invoking the context’s save() method, or rely on the context’s implicit save behavior instead.
            // Contexts automatically track changes to their known model instances and include those changes in subsequent saves.
            // vIn addition to saving, you can use a context to fetch, enumerate, and delete model instances. For more information, see ModelContext.
            modelContext.insert(newItem)
        }
    }

    private func deleteItems(offsets: IndexSet) {
        withAnimation {
            for index in offsets {
                modelContext.delete(items[index])
            }
        }
    }
}

#Preview {
    ContentView()
        .modelContainer(for: Item.self, inMemory: true)
}
